package com.app.controller.teacher;

import com.app.pojo.*;
import com.app.service.Information.CollegeService;
import com.app.service.Information.MajorService;
import com.app.service.student.ManagementService;
import com.app.service.teacher.TeacherLoginService;
import com.app.service.teacher.TeacherService;
import com.app.tools.Excel;
import com.app.tools.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    TeacherLoginService teacherLoginService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    ManagementService managementService;
    @Autowired
    CollegeService collegeService;
    @Autowired
    MajorService majorService;

    @PostMapping("/teacherLogin")
    public String teacherLogin(String userId , String password, HttpSession session, Model model){
        Teacher teacher = teacherLoginService.login(userId,password);
        if(teacher!=null){
           if(teacher.getType()==1){
                model.addAttribute("error","账号被冻结");
                return "redirect:/teacher/login";
            }else {
               session.setAttribute("teacher",teacher);
               return "redirect:/teacher/index";
           }
        }else{
            model.addAttribute("error", "账号或密码错误!!!");
            return "redirect:/teacher/login";
        }
    }

    @PostMapping("/update")
    public String updateInfo(Integer id,String teacherId,String name,Integer sex,
                             String mobilePhone,Model model,HttpSession session){
        String error =  teacherService.updateInfo(id,name,sex,mobilePhone);
        Teacher teacher = teacherService.getTeacherById(teacherId);
        model.addAttribute("error",error);;
        session.setAttribute("teacher",teacher);
        return "teacher/common/teacherInfo";
    }

    @GetMapping("/index")
    public String index() {
        return "/teacher/main";
    }

    @RequestMapping(value = "/list")
    public String appList() {
        return "teacher/common/teacherInfo";
    }

    @RequestMapping(value = "toPassword")
    public String toPassword(){
        return "teacher/common/teacherPassword";
    }

    @RequestMapping("updatePassword")
    public String updatePassword(Integer id,String oldPassword,
                                 String newPassword,Model model){
        String error = teacherService.updatePassword(id,oldPassword,newPassword);
        model.addAttribute("error",error);
        if(error.equals("密码修改成功,请重新登录")){
            return "redirect:/teacher/login";
        }
        return "teacher/common/teacherPassword";
    }

    @RequestMapping("showStudent")
    public String showStudent(Model model,String teacherId,String name,
                              Integer sex, String major, String year,
                              @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum){
        try {
        List<Student> students = managementService.getStudents(teacherId,name,sex,major,year);
        List<Major> majors = majorService.getMajorsByCollege(students.get(0).getCollege());
        //分页
            PageInfo pageInfo = new PageInfo(pageNum,students);
            model.addAttribute("pageInfo",pageInfo);
            model.addAttribute("majors",majors);
        }catch (Exception e){
            return "teacher/common/showStudent";
        }
        return "teacher/common/showStudent";
    }

    @RequestMapping("studentInfo")
    public String studentInfo(Model model,Integer stuId){
        Student student = managementService.getStudentById(stuId);
        Grade grade = managementService.getGrade(student.getUserId());
        model.addAttribute("grade",grade);
        model.addAttribute("student",student);
        return "teacher/common/studentInfo";
    }

    @RequestMapping("toUpdate")
    public String toUpdate(Model model,Integer stuId){
        Student student = managementService.getStudentById(stuId);
        Grade grade = managementService.getGrade(student.getUserId());
        List<College> colleges = collegeService.getColleges();
        List<Major> majors = majorService.getMajorsByCollege("");
        model.addAttribute("grade",grade);
        model.addAttribute("majors",majors);
        model.addAttribute("colleges",colleges);
        model.addAttribute("student",student);
        return "teacher/common/studentUpdate";
    }
    @RequestMapping("studentUpdate")
    public String studentUpdate(Model model,Student student,Grade grade){
        Integer srow = managementService.updateStudent(student);
        grade.setRanking(0);
        Integer grow =  teacherService.updateStudentGrade(grade,student.getClasss());
        if(srow<1){
            model.addAttribute("sError","学生信息保存有误");
        }else {
            model.addAttribute("sError","学生信息保存成功");
        }
        if(grow<1){
            model.addAttribute("gError","成绩保存有误");
        }else {
            model.addAttribute("gError","成绩保存成功");
        }
        return toUpdate(model,student.getId());
    }

    @RequestMapping("toStudentAdd")
    public String toStudentAdd(Model model){
        List<Major> majors = majorService.getMajorsByCollege("");
        List<College> colleges = collegeService.getColleges();
        List<Teacher> teachers = teacherService.getTeachers();
        model.addAttribute("majors",majors);
        model.addAttribute("colleges",colleges);
        model.addAttribute("teachers",teachers);
        return "teacher/common/studentAdd";
    }

    @RequestMapping("portExcel")
    public String portExcel(Model model ,String path){
        String [] herder = {"学号","姓名","学院","入学年份(xx级)","班级","专业","性别(0,1)","手机号","教师Id"};
        Excel portExcel = new Excel();
        try {
            OutputStream out = new FileOutputStream(path+"\\学生样式表.xls");
            portExcel.exportExcel(out,herder);
        } catch (Exception e) {
            model.addAttribute("eError","导出时发送未知异常");
            return toStudentAdd(model);
        }
        model.addAttribute("eError","导出成功");
        return toStudentAdd(model);
    }

    @RequestMapping("exParseExcel")
    public String exParseExcel(Model model, String excel){
        Excel portExcel = new Excel();
        List<String[]> list;
        int rows=0;
        try {
            InputStream inputStream = new FileInputStream(excel);
            String suffix = excel.substring(excel.indexOf("."));
            list = portExcel.exParseExcel(inputStream,suffix,1);
        } catch (Exception e) {
            model.addAttribute("eError","导入时发送未知异常");
            return toStudentAdd(model);
        }
            String isOk = excleIsOk(list);
            if(!isOk.equals("")){
                model.addAttribute("eError","第"+isOk.substring(0,isOk.length()-1)+"行不符合要求,请检查excel表");
                return toStudentAdd(model);
            }else{
                Student student;
                for(String[] ss:list){
                    student = new Student(ss[0],ss[1],ss[2],ss[3],
                            ss[4],ss[5],Integer.parseInt(ss[6]),ss[7],ss[0],ss[8]);
                   rows += managementService.addStudent(student);
                    model.addAttribute("eError","添加成功,共有"+rows+"行受影响");
                }
                return toStudentAdd(model);
            }
    }

    @RequestMapping("addStudent")
    public String addStudent(Model model,Student student){
        Integer row = managementService.addStudent(student);
        if(row<1){
            model.addAttribute("error","添加失败");
        }else {
            model.addAttribute("error","添加成功");
        }
        return toStudentAdd(model);
    }

    @RequestMapping("delStudent")
    public String delStudent(Model model,Integer stuId){
        int row = managementService.delStudent(stuId);
        if(row<1){
            model.addAttribute("error","删除时发送未知异常");
        }else {
            model.addAttribute("error","删除成功");
        }
        return showStudent(model,"","",null,"","",1);
    }

    @GetMapping("/logout")
    public String teacherLogout(HttpSession session) {
        session.invalidate();
        return "redirect:/teacher/login";
    }

    //用于判断Excel是否正确
    public String excleIsOk(List<String[]> list){
        String noRow="";
        int row=2;
        Student student;
        Major major;
        Teacher teacher;
        for(String[] ss:list){
            student = managementService.getStudentById(Integer.parseInt(ss[0]));
            major = majorService.getMajorByCollege(ss[2],ss[5]);
            teacher = teacherService.getTeacherById(ss[8]);
            if(major==null || teacher==null || student!=null){
                    noRow += row+",";
            }
            row++;
        }
        return noRow;
    }

    @RequestMapping("toShowGrade")
    public String toShowGrade(Model model,String college){
        List<College> colleges = collegeService.getColleges();
        Grade grade = teacherService.getAVGGradeByCollege(college);
        model.addAttribute("show",college);
        model.addAttribute("colleges",colleges);
        model.addAttribute("grade",grade);
        return "teacher/common/showGrade";
    }

}
